package com.enbatis.mybatisplugs.service.impl;

import com.enbatis.mybatisplugs.base.Account;
import com.enbatis.mybatisplugs.base.BaseServiceImpl;
import com.enbatis.mybatisplugs.base.IRedisService;
import com.enbatis.mybatisplugs.commons.sql.Wrapper;
import com.enbatis.mybatisplugs.entity.SysUser;
import com.enbatis.mybatisplugs.service.SysResourceService;
import com.enbatis.mybatisplugs.service.SysRoleRelResourceService;

import com.enbatis.mybatisplugs.entity.SysRoleRelResource;
import com.enbatis.mybatisplugs.mapper.SysRoleRelResourceMapper;
import com.enbatis.mybatisplugs.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
* 描述：
* @author wangweidong
* @date 2019-06-18 12:43:21
*/

@Service
public class SysRoleRelResourceServiceImpl extends BaseServiceImpl<SysRoleRelResourceMapper,SysRoleRelResource > implements SysRoleRelResourceService {

    @Autowired
    private IRedisService redisService;
    @Autowired
    private SysResourceService sysResourceService;

    @Override
    public boolean addRoleResource(Long roleId, Long[] resourceIds, Account sysUser) {
        List<SysRoleRelResource> sysRoleRelResources=list(new Wrapper<>(new SysRoleRelResource()).eq("role_id",roleId));
        List<SysRoleRelResource> saveList=new ArrayList<>();
        if (CollectionUtils.isEmpty(sysRoleRelResources)){

            for (Long rid:resourceIds) {
                SysRoleRelResource roleRelResource=new SysRoleRelResource();
                roleRelResource.setRoleId(roleId);
                roleRelResource.setDeleted(0);
                roleRelResource.setResourceId(rid);
                saveList.add(roleRelResource);
            }
        }else{
            for (SysRoleRelResource relResource:sysRoleRelResources) {
                this.deleteById(relResource.getId());
            }
            for (Long rid:resourceIds) {
                SysRoleRelResource roleRelResource=new SysRoleRelResource();
                roleRelResource.setRoleId(roleId);
                roleRelResource.setDeleted(0);
                roleRelResource.setResourceId(rid);
                saveList.add(roleRelResource);
            }

        }

      int num=  this.saveBatch(saveList);
        return num>0;
    }
}
